package utils

import (
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
	"time"
)

var InvalidWordMap map[string]int

func Log(format string, v ...interface{}) {
	txt := fmt.Sprintf(format, v...)
	fmt.Println(txt)
}

func TimeFormat(t int64) string {
	zone1, _:= time.LoadLocation("")
	time1 := time.Unix(t, 0)
	d := "d"
	day := t/(24*60*60)
	if day >=10 {
		d =  strconv.FormatInt(day,10) + "d"
	}else {
		d =  "0" + strconv.FormatInt(day,10) + "d"
	}
	h := "h"
	if time1.In(zone1).Hour() >= 10 {
		h = strconv.Itoa(time1.In(zone1).Hour()) + "h"
	}else {
		h = "0" + strconv.Itoa(time1.In(zone1).Hour()) + "h"
	}
	m := "m"
	if time1.In(zone1).Minute() >= 10 {
		m = strconv.Itoa(time1.In(zone1).Minute()) + "m"
	}else {
		m = "0" + strconv.Itoa(time1.In(zone1).Minute()) + "m"
	}
	s := "s"
	if time1.In(zone1).Second() >= 10 {
		s = strconv.Itoa(time1.In(zone1).Second()) + "s"
	}else {
		s = "0" + strconv.Itoa(time1.In(zone1).Second()) + "s"
	}
	return fmt.Sprintf("%s %s %s %s", d, h, m, s)
}

func LoadInvalidWordMap()  {
	InvalidWordMap = make(map[string]int)
	b, err := ioutil.ReadFile("./list.txt")
	if err != nil {
		Log("read file: %v error: %v", "./list.txt", err)
		return
	}
	s := string(b)
	for _, lineStr := range strings.Split(s, "\n") {
		if lineStr == "" {
			continue
		}
		InvalidWordMap[lineStr] = 1
	}
}

func CheckInvalidWord(str string) string {
	if str == "" {
		return str
	}

	len := len(str)
	// 长度从len -> 1;
	for i:=len; i>0; i-- {
		// 起点从0 -> len-i;
		for  j:=0; j<=len-i; j++ {
			substr := str[j:i+j]
			_,exist := InvalidWordMap[substr]
			if exist {
				prev := str[0:j]
				curr := strings.Repeat("*",i)
				next := str[i+j:len]
				return CheckInvalidWord(prev) + curr + CheckInvalidWord(next)
			}
		}
	}

	return str;
}